package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.FeeListVo;
import com.antdesignbackend.backend.entity.entityVo.FeeVo;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/fee")
public class FeeController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    @Autowired
    private FeeService feeService;
    @Autowired
    private FeeListService feeListService;
    @Autowired
    private FeeTypeService feeTypeService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private SettingService settingService;
    //也可以直接注入mapper来进行操作
    // @Autowired
    //userDemoMapper userDemoMapper;
    /**
     *收费录入
     */
    @GetMapping("/index")
    @AuthToken
    public String index() {
        // ModelAndView modelAndView = new ModelAndView("client/index");
        return "fee/index";
    }
    /**
     *收费录入
     */
    @GetMapping("/reportIndex")
    @AuthToken
    public String reportIndex() {
        // ModelAndView modelAndView = new ModelAndView("client/index");
        return "fee/reportIndex";
    }

    /***
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (feeService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }

    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody FeeVo data) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<FeeVo> datalist=new ArrayList<>();
        QueryWrapper<FeeVo> wrapper =new QueryWrapper<>();
        if(data.getStartMonth()!=null && !data.getStartMonth().equals(""))
        {
            String start=data.getStartMonth()+"-01";
            wrapper.ge("t.feeData",start);
        }
        if(data.getEndMonth()!=null && !data.getEndMonth().equals(""))
        {
            String end=data.getEndMonth()+"-01";
            wrapper.le("t.feeData",end);
        }
        if(data.getShopId()!=null)
        {
            wrapper.eq("t.shopId",data.getShopId());
        }
        if(data.getFeeYearMonth()!=null && !data.getFeeYearMonth().equals(""))
        {
            wrapper.eq("t.feeYearMonth",data.getFeeYearMonth());
        }
        if(data.getState() != null && data.getState() == 1) //缴费
        {
            wrapper.eq("t.dueAmount",0);
        }
        if(data.getState() != null && data.getState() == 0) //欠费
        {
            wrapper.gt("t.dueAmount",0);
        }
//        if(data.getName()!=null&& !data.getName().equals(""))
//        {
//            //wrapper.and(wra -> wra.le("t.createTime",data.getEndTime()));
//            wrapper.like("t.name",data.getName());
//        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=feeService.countView(wrapper);
        result.setTotal(total);
        //再查询
        if(total>=0)
        {
            datalist= feeService.searchView(wrapper.orderByAsc("t.feeData"),new Page<>(data.getPageIndex(),data.getPageSize()));
             for (FeeVo item1:datalist) {
                QueryWrapper<FeeList> wrapperfeeList =new QueryWrapper<>();
                wrapperfeeList.eq("feeAutoKey",item1.getAutoKey());
                item1.setFeeList(feeListService.list(wrapperfeeList));
            }
//            List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//            datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;


    }
    /***
     * 新增/修改保存
     * id 0是新增加，否则修改
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody FeeVo vo) throws Exception {
        result = new ReturnVO();
        QueryWrapper<FeeVo> queryWrapper=new QueryWrapper<>();
        queryWrapper.and(i -> i.eq("feeYearMonth", vo.getFeeYearMonth()).eq("shopId",vo.getShopId()));
        if (feeService.count(queryWrapper)>0){
            result.setCode("502");
        }else {
            boolean b = false;
            Fee entity = new Fee();
            long random = System.currentTimeMillis();
            String dateKey = random + "";
            Settings seting = settingService.getById(1);
            Integer oneday = 0;
            Integer towday = 0;
            Integer threeday = 0;
            String hour = "00:00";
            if (seting != null) {
                oneday = seting.getNotityDay1();
                towday = seting.getNotityDay2();
                threeday = seting.getNotityDay3();
                hour = seting.getOffTime();
            }
            //新增
            String datastr = vo.getFeeYearMonth() + "-01";
            Date feedata = CalendarDate.strToDate(datastr, "yyyy-MM-dd");
            Date beginduedate = CalendarDate.addDate(feedata, "month", 1);
            Date begindueone = null;
            Date beginduetow = null;
            Date beginduethree = null;
            if (oneday != null)
                begindueone = CalendarDate.addDate(beginduedate, "day", oneday);
            if (towday != null)
                beginduetow = CalendarDate.addDate(beginduedate, "day", towday);
            if (threeday != null)
                beginduethree = CalendarDate.addDate(beginduedate, "day", threeday);
            Date offtime = begindueone;
            if (beginduetow != null && beginduetow.after(offtime))
                offtime = beginduetow;
            if (beginduethree != null && beginduethree.after(offtime))
                offtime = beginduethree;

            if (offtime == null)
                offtime = beginduedate;
            offtime = CalendarDate.addDate(offtime, "day", 1);
            String offtimestr = CalendarDate.dateToStr(offtime, "yyyy-MM-dd") + " " + hour + ":00";
            Date offDate = CalendarDate.strToDate(offtimestr, "yyyy-MM-dd HH:mm:ss");

            entity.setAutoKey(dateKey);
            entity.setShopId(vo.getShopId());
            entity.setFeeYearMonth(vo.getFeeYearMonth());
            entity.setCreateTime(new Date());
            entity.setFeeData(feedata);
            entity.setBeginDueDate(beginduedate);
            entity.setSendDate1(begindueone);
            entity.setSendDate2(beginduetow);
            entity.setSendDate3(beginduethree);
            entity.setOffDate(offDate);
            entity.setMessageNum(0);
            b = feeService.save(entity);
            //后面要改成事务 todo
            if (vo.getAmountList() != null && vo.getAmountList().size() > 0) {
                for (int i = 0; i < vo.getAmountList().size(); i++) {
                    FeeList entitylist = new FeeList();
                    entitylist.setFeeAutoKey(dateKey);
                    entitylist.setFeeType(vo.getAmountStr().get(i));
                    entitylist.setAmount(vo.getAmountList().get(i));
                    entitylist.setState(0);
                    feeListService.save(entitylist);
                }
            }
            if (b == true) {
                result.setMessage("保存成功！");
                result.setCode("200");
            } else {
                result.setMessage("保存失败！");
                result.setCode("500");
            }
        }
        return result;
    }
    /***
     * 操作相关，通过action 区分
     * @return
     */
    @PostMapping("/action")
    @ResponseBody
    @AuthToken
    public ReturnVO actions(@RequestBody FeeVo vo) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        String msg=null;
        switch (vo.getAction())
        {
            case "changeList":
                //缴费状态
                b=feeListService.update(new UpdateWrapper<FeeList>().set("state", vo.getState()).eq("id", vo.getId()));
                break;
            case "updatefeelist":
                //一键交清
                b=feeListService.update(new UpdateWrapper<FeeList>().set("state", 1).eq("feeAutoKey", vo.getAutoKey()));
                break;
            default:
                break;
        }

        if(b==true){
            result.setCode("200");
            if(msg==null)
            {
                result.setMessage("保存成功！");
            }
            else
            {
                result.setMessage(msg);
            }

        }
        else
        {
            result.setCode("500");
            if(msg==null)
            {
                result.setMessage("保存失败！");
            }
            else
            {
                result.setMessage(msg);
            }

        }
        return result;
    }
    /***
     * 获取收费报表图表数据
     * @return
     */
    @PostMapping("/getFeeListMap")
    @ResponseBody
    public Map<String, Object> getFeeListMap(@RequestBody FeeListVo vo) throws Exception {
        Map<String, Object> resultmap= new HashMap<>();
        List<String> typenames=new ArrayList<>();
        List<String> shopnames=new ArrayList<>();
        //先获取收费类目
        List<FeeType> typeList = new ArrayList<>();
        QueryWrapper<FeeType> wrapper =new QueryWrapper<>();
        wrapper.eq("state",1);
        try
        {
            //项目类别
            typeList = feeTypeService.getBaseMapper().selectList(wrapper.orderByAsc("sorts"));
            if(typeList.size()==0) return resultmap;
            for (FeeType item1:typeList) {
                typenames.add(item1.getName());
            }
            typenames.add("总费用");
            resultmap.put("typenames",typenames);
            //店铺
            QueryWrapper<Shop> wrappershop =new QueryWrapper<>();
            wrappershop.eq("state",1);
            List<Shop> shopList = shopService.getBaseMapper().selectList(wrappershop);
            if(shopList.size()==0) return resultmap;
            for (Shop item2:shopList) {
                shopnames.add(item2.getName());
            }
            resultmap.put("shopnames",shopnames);

            QueryWrapper<FeeListVo> wrapperlist =new QueryWrapper<>();
             if(vo.getStartmonth()!=null && !vo.getStartmonth().equals(""))
             {
                 String start=vo.getStartmonth()+"-01";
                 wrapperlist.ge("t.feeData",start);
             }
            if(vo.getEndmonth()!=null && !vo.getEndmonth().equals(""))
            {
                String end=vo.getEndmonth()+"-01";
                wrapperlist.le("t.feeData",end);
            }
            List<FeeListVo> datafeelist=feeListService.searchView(wrapperlist,new Page<>(1,99999));
            List<Object> series=new ArrayList<>();
            Map<String,Object> valueItem1=new HashMap();
            List<Double> amountList=new ArrayList<>();
            for (FeeType item1:typeList) {
                valueItem1=new HashMap();
                valueItem1.put("name",item1.getName());
                valueItem1.put("type","bar");
                amountList=new ArrayList<>();
                for (Shop item2:shopList) {
                    List<FeeListVo> filterdata=datafeelist.stream().filter(s->s.getFeeType().equals(item1.getName()) && s.getShopId()==item2.getId()).collect(Collectors.toList());
                  if(filterdata.size()>0)
                  {
                      amountList.add(filterdata.stream().mapToDouble(FeeListVo::getAmount).sum());
                  }
                    else
                  {
                      amountList.add(0.0);
                  }
                }
                valueItem1.put("data",amountList);
                series.add(valueItem1);
            }

            //总费用
            valueItem1=new HashMap();
            valueItem1.put("name","总费用");
            valueItem1.put("type","bar");
            amountList=new ArrayList<>();
            for (Shop item2:shopList) {
                List<FeeListVo> filterdata=datafeelist.stream().filter(s->s.getShopId()==item2.getId()).collect(Collectors.toList());
                if(filterdata.size()>0)
                {
                    amountList.add(filterdata.stream().mapToDouble(FeeListVo::getAmount).sum());
                }
                else
                {
                    amountList.add(0.0);
                }
            }
            valueItem1.put("data",amountList);
            series.add(valueItem1);
            //总费用*********
           resultmap.put("series",series);

        }
        catch(Exception ex)
        {
            logger.error(ex.getMessage());
        }

        return resultmap;
    }
}
